package com.nosweattechnet.mapmyway;

import java.util.ArrayList;
import java.util.concurrent.ExecutionException;

import android.app.ListActivity;
import android.app.SearchManager;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import com.nosweattechnet.datatypes.Place;
import com.nosweattechnet.server.PlaceSearchAsyncTask;

public class PlaceSearch extends ListActivity {	
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    
	    //Gets the keyword to search for
		Intent intent = getIntent();
		if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
			String query = intent.getStringExtra(SearchManager.QUERY);
			doPlaceSearch(query);
		}
    }
    
    //Searches for a given keyword then adds all of the results to the main map
    public void doPlaceSearch(String query) {
    	//Starts the search
    	PlaceSearchAsyncTask psat = new PlaceSearchAsyncTask(query);
    	psat.execute();
    	
    	ArrayList<Place> placeObjects = new ArrayList<Place>();
    	
    	//Retrieves the list of places
    	try {
    		placeObjects = psat.getPlaces();
    	}
    	catch (InterruptedException e) {}
    	catch (ExecutionException e) {}
    	
    	//if the search returned no Places the user is notified
    	if(placeObjects.size()<=0){
    		Toast.makeText(this,R.string.no_search_results,Toast.LENGTH_LONG).show();
    		finish();
    	}
    	
    	//All of the places returned are added to the main map
    	DisplayPlaces.clear();
    	DisplayPlaces.addPlaces(placeObjects);
    	finish();   	
    	
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_search_items, menu);
        return true;
    }

    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                NavUtils.navigateUpFromSameTask(this);
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

}
